<?php

namespace App\Observers;
use App\Models\Fang;
use GuzzleHttp\Client;
class FangObserver
{
    # 添加入库前
    public function creating(Fang $fang){
        $fang->fang_config = implode(",",request()->get("fang_config"));
        # 得到请求的url地址
        $url = config("geo.http");
        $address = request()->get("fang_addr");
        $city = request()->get("fang_city");
        # 把url里面的%s点位替换
        $url = sprintf($url,$address,$city);
        # 发送请求
        $client = new Client(["timeout" => 5,"verify" => false]);
        $res = $client->get($url);
        $json = (string)$res->getBody();
        # 转为经纬度
        $arr = json_decode($json,true);
        $location = count($arr["geocodes"]) > 0 ? $arr["geocodes"][0]["location"] :"0,0";
        $arr = explode(",",$location);
        $fang->longitude = $arr[0];
        $fang->latitude = $arr[1];
    }
    # 添加入库后
//    public function create(Fang $fang){
//        $id = $fang->id;
//        $name = $fang->fang_name;
//        $desn = $fang->fang_desn;
//        $http = config("es.hosts");
//        $client = \Elasticsearch\ClientBuilder::create()->setHosts($http)->build();
//        # 写入文档
//        $params = [
//            'index' => 'zfw',
//            'id' => $id,
//            'body' => [
//                'title' => $name,
//                'desn' => $desn,
//            ],
//        ];
//        $client->index($params);
//    }
    # 修改入库
    public function updating(Fang $fang){
        $this->creating($fang);
    }
}
